//
//  AppDelegate.m
//  XDBaseFrameWork
//
//  Created by XD-XY on 9/18/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//

#import "AppDelegate.h"
#import "GuideViewController.h"
#import "SecondViewController.h"

#import "APService.h"

#import "AlixPayResult.h"//支付宝

#import "orderDetailViewController.h"

#import "ChooseImageViewController.h"

#import "OrderConfirmViewController.h"

#import "YouHuiQuanViewController.h"

#import "APPointmentHospitalViewController.h"

#import "UMSocial.h"
#import "UMSocialWechatHandler.h"

BMKMapManager* _mapManager;
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    
    // 要使用百度地图，请先启动BaiduMapManager
	_mapManager = [[BMKMapManager alloc]init];
    
	BOOL ret = [_mapManager start:@"snelzlPC3U3YmdEHUjWq13UI" generalDelegate:self];
	if (!ret) {
		NSLog(@"manager start failed!");
	}
    
    //设置根视图
    if (GUIDECOUNT==0){
        SETSTATUSBARHIDDEN(NO);
        self.tabBarController = [XDTabBarViewController sharedXDTabBarViewController];
        self.rootNav = [[UINavigationController alloc] initWithRootViewController:_tabBarController];
        _rootNav.navigationBarHidden=YES;
        self.window.rootViewController = _rootNav;
    }else{
        if (![[NSUserDefaults standardUserDefaults] objectForKey:ISFIRSTSTART]){
            SETSTATUSBARHIDDEN(YES);
            GuideViewController * guideView = [[GuideViewController alloc] init];
            self.window.rootViewController = guideView;
        }else{
            SETSTATUSBARHIDDEN(NO);
            self.tabBarController = [XDTabBarViewController sharedXDTabBarViewController];
            self.rootNav = [[UINavigationController alloc] initWithRootViewController:_tabBarController];
            _rootNav.navigationBarHidden=YES;
            self.window.rootViewController = _rootNav;
        }
    }
    
    //设置友盟AppKey
    [UMSocialData setAppKey:UMAPPKEY];
    //设置微信AppId
    //    [UMSocialConfig setWXAppId:WEIXINAPPID url:nil];
    [UMSocialWechatHandler setWXAppId:WEIXINAPPID appSecret:WEIXINSECRET url:nil];

    [XDTools moveFileToDocument:@"area" andType:@"db"];
    
    //jpush 1
    [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeAlert)];
    [APService setupWithOption:launchOptions];
    
    if(ISLOGING){
        NSString * uid = [[NSUserDefaults standardUserDefaults] objectForKey:kMY_USER_ID];
        NSString * string = [NSString stringWithFormat:@"%@",uid];
        [APService setTags:[NSSet setWithObject:[NSString stringWithFormat:@"%@",string]] callbackSelector:nil object:nil];
    }else{
        [APService setTags:[NSSet setWithObject:@""] callbackSelector:nil object:nil];
    }


    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    //jpush 2
    [APService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    
    [APService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNoData);
    
    // order 订单列表    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    if (application.applicationState ==UIApplicationStateInactive ){
        //用户从后台进入
        if ([userInfo[@"type"] isEqualToString:@"order"]){  //进入我的订单
            
            [[XDTabBarViewController sharedXDTabBarViewController] confirmSelectTabBar:1];
            [[XDTabBarViewController sharedXDTabBarViewController] setSelectedIndex:1];
            
        }else if ([userInfo[@"type"] isEqualToString:@"voucher"]){ //进入优惠劵
            YouHuiQuanViewController * yvc = [[YouHuiQuanViewController alloc] init];
            [_rootNav pushViewController:yvc animated:YES];
        }
        
    }else if (application.applicationState ==UIApplicationStateActive){
        //用户一直活跃在前台
        if ([XDTabBarViewController sharedXDTabBarViewController].presentIndex == 1){
            [XDTabBarViewController sharedXDTabBarViewController].reminder_IV.hidden = YES;
        }else{
            [XDTabBarViewController sharedXDTabBarViewController].reminder_IV.hidden = NO;
        }
    }
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;

    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;

    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized){
        DDLOG(@"定位服务开启了");

        [XDTools sharedXDTools].longitude = [[[NSUserDefaults standardUserDefaults] valueForKey:@"longitude"] floatValue];
        [XDTools sharedXDTools].latitude = [[[NSUserDefaults standardUserDefaults] valueForKey:@"latitude"] floatValue];
    }else{
        DDLOG(@"定位服务关闭了");
        [XDTools sharedXDTools].longitude = 0;
        [XDTools sharedXDTools].latitude = 0;
    }
    
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

//openURL:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    NSString *string = [NSString stringWithFormat:@"%@",url];
    string = [string substringToIndex:2];
    if([string isEqualToString:@"co"]){
        [self parse:url application:application];
        return YES;
    }
    return YES;
    
}

- (void)reSetRootView{
    SETSTATUSBARHIDDEN(NO);
    self.tabBarController = [XDTabBarViewController sharedXDTabBarViewController];
    self.rootNav = [[UINavigationController alloc] initWithRootViewController:_tabBarController];
    _rootNav.navigationBarHidden=YES;
    self.window.rootViewController = _rootNav;
}

//百度地图
- (void)onGetNetworkState:(int)iError
{
    if (0 == iError) {
        NSLog(@"联网成功");
    }
    else{
        NSLog(@"onGetNetworkState %d",iError);
    }
    
}

- (void)onGetPermissionState:(int)iError
{
    if (0 == iError) {
        NSLog(@"授权成功");
    }
    else {
        NSLog(@"onGetPermissionState %d",iError);
    }
}

//客户端回调

- (void)parse:(NSURL *)url application:(UIApplication *)application {
    
    ChooseImageViewController *chooseImageVC = [[XDTools sharedXDTools] chooseImageVC];
    
    orderDetailViewController *orderDetailVC = [[XDTools sharedXDTools] orderDetailVC];
    
    OrderConfirmViewController *orderConfirmVC = [[XDTools sharedXDTools] OrderConfirmVC];
    
    APPointmentHospitalViewController * apvc = [XDTools sharedXDTools].hospitalVC;
    
    //结果处理
    AlixPayResult* result = [self handleOpenURL:url];
    
	if (result)
    {
        
		if (result.statusCode == 9000)
        {
            
            //跳到订单
            
            [XDTools showTips:@"支付成功" toView:self.window];

            if (chooseImageVC!=nil) {
                [chooseImageVC freshRootVC];
                return;
            }
            
            if (orderDetailVC!=nil) {
                [orderDetailVC refreshOrderStatus];
                return;
            }
            
            if (orderConfirmVC!=nil) {
                [orderConfirmVC refreshOrderConfirmStatus];
                return;
            }
            
            if (apvc!=nil){
                [apvc goToOrderList];
            }
			/*
			 *用公钥验证签名 严格验证请使用result.resultString与result.signString验签
			 */
            
            //交易成功
            //            NSString* key = @"签约帐户后获取到的支付宝公钥";
            //			id<DataVerifier> verifier;
            //            verifier = CreateRSADataVerifier(key);
            //
            //			if ([verifier verifyString:result.resultString withSign:result.signString])
            //            {
            //                //验证签名成功，交易结果无篡改
            //			}
            
        }
        else
        {
            //交易失败
            [XDTools showTips:@"支付未成功" toView:self.window];
            
            if (orderConfirmVC!=nil) {
                [orderConfirmVC goToOrderList];
                [XDTools sharedXDTools].OrderConfirmVC = nil;
            }
            
        }
    }
    else
    {
        //失败
        [XDTools showTips:@"请重新交易" toView:self.window];
    }
    
}

- (AlixPayResult *)resultFromURL:(NSURL *)url {
	NSString * query = [[url query] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
#if ! __has_feature(objc_arc)
    return [[[AlixPayResult alloc] initWithString:query] autorelease];
#else
	return [[AlixPayResult alloc] initWithString:query];
#endif
}

- (AlixPayResult *)handleOpenURL:(NSURL *)url {
	AlixPayResult * result = nil;
	
	if (url != nil && [[url host] compare:@"safepay"] == 0) {
		result = [self resultFromURL:url];
	}
    
	return result;
}

@end
